import { Provide } from '@midwayjs/core';
import { Like, Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { ImagesEntity } from '../entity/images.entity';
import { PagingInfo } from '../dto/images';

@Provide()
export class ImagesService {
  @InjectEntityModel(ImagesEntity)
  imagesModel: Repository<ImagesEntity>;

  //添加图片
  async addImages(s: ImagesEntity) {
    s.id = null;
    // 插入数据
    return await this.imagesModel.insert(s);
  }

  //获取图片列表
  async getImages(pagingInfo: PagingInfo, userID?: number, images?: Partial<ImagesEntity>) {
    const idIsUndefined = userID == undefined;
    const where: any = { ...images, user: { id: userID } };
    if (images.name) where.name = Like(`%${images.name}%`);
    const [results, total] = await this.imagesModel.findAndCount({
      where: where,
      order: { id: 'ASC' },
      relations: ['user'],
      select: {
        user: { id: idIsUndefined, email: idIsUndefined },
      },
      skip: pagingInfo.skip * pagingInfo.take,
      take: pagingInfo.take,
    });
    const totalPages = Math.ceil(total / pagingInfo?.take);
    const remainingPages = totalPages - (pagingInfo.skip + 1);
    return {
      results,
      total,
      totalPages,
      remainingPages,
    };
  }

  //根据ID 删除图片
  async delete(id: number) {
    return this.imagesModel.delete(id);
  }


}
